import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

declare let $;

@Component({
  selector: 'app-code-info',
  templateUrl: './code-info.component.html',
  styleUrls: ['./code-info.component.scss']
})
export class CodeInfoComponent implements OnInit {

  @Input()
  isVisible = false;

  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();

  // 二维码内容
  @Input()
  qrCodeContent: any;

  // 下载文件的名称
  @Input()
  fileName: any;

  constructor() {
  }

  ngOnInit() {
  }

  handleOk(): void {
    this.isVisible = false;
    this.emitVisible.emit(this.isVisible);
  }

  handleCancel(): void {
    this.isVisible = false;
    this.emitVisible.emit(this.isVisible);
  }

  img(str) {
    var out, i, len, c;
    out = '';
    len = str.length;
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        out += str.charAt(i);
      } else if (c > 0x07FF) {
        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      } else {
        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      }
    }
    return out;
  }

  createImg(size) {
    var that = this;
    // let qrCode = this.qrCode.code;
    $('#text').html('');
    let qrcodewidth = size;
    let qrcodeheight = size;
    let url = this.qrCodeContent;
    let qrcode = $('#text').qrcode({
      render: 'canvas',
      text: this.img(url),
      width: qrcodewidth,
      height: qrcodeheight,
      background: '#ffffff',
      foreground: '#000000',
    });
    //canvas宽高
    let canvaswidth = qrcodewidth;
    let canvasheight = qrcodeheight;
    let canvas = qrcode.find('canvas').get(0);
    let img = new Image();
    img.src = canvas.toDataURL('image/png');
    img.onload = function() {
      canvas.width = canvaswidth;
      canvas.height = canvasheight;
      let ctx = canvas.getContext('2d');
      //设置画布背景
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      //绘制二维码
      ctx.drawImage(img, 0, 0);
      let type = 'png';
      let imgFile = $('#text canvas').get(0).toDataURL();
      // 下载
      let link = document.createElement('a');
      // 设置下载内容（可以是网址）
      link.href = imgFile;
      // 设置文件名称
      link.download = that.fileName + '.' + type;
      let event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      link.dispatchEvent(event);
    };
  }

  renderCode() {
    console.log(this.qrCodeContent);
    $('#qrcode').html('');
    $('#qrcode').qrcode({width: 120, height: 120, text: this.qrCodeContent});
  }
}
